package com.yanliang.server;

import com.yanliang.handler.UserServerHandler;
import com.yanliang.model.RpcRequest;
import com.yanliang.serializer.JSONSerializer;
import com.yanliang.serializer.RpcDecoder;
import com.yanliang.service.UserServiceImpl;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author yanliang
 * @date 5/23/20203:00 PM
 */
@Slf4j
@Component
public class ServerBootstrap implements InitializingBean, ApplicationContextAware {

	@Autowired
	private UserServiceImpl userServiceImpl;

	private ApplicationContext applicationContext;

	//hostName:ip地址  port:端口号
	public void startServer() throws InterruptedException {
		new Thread(()->{
			NioEventLoopGroup bossGroup = new NioEventLoopGroup();
			NioEventLoopGroup workerGroup = new NioEventLoopGroup();
			try {
				io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
				serverBootstrap.group(bossGroup, workerGroup)
						.channel(NioServerSocketChannel.class)
						.childHandler(new ChannelInitializer<SocketChannel>() {
							protected void initChannel(SocketChannel ch) throws Exception {
								ChannelPipeline pipeline = ch.pipeline();
								pipeline.addLast(new StringEncoder());
								pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
								pipeline.addLast(new UserServerHandler(applicationContext));

							}
						});
				// todo 暂时写死
				ChannelFuture cf =serverBootstrap.bind("127.0.0.1", 8990).sync();
			}catch (InterruptedException e) {
				e.printStackTrace();
				bossGroup.shutdownGracefully();
				workerGroup.shutdownGracefully();
			}
		}).start();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		startServer();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
